package org.bunny.vehicle.service.admin;

import java.util.Date;

import org.bunny.vehicle.entity.User;
import org.bunny.vehicle.service.BaseService;
import org.bunny.vehicle.util.Const;
import org.bunny.vehicle.util.JSON;
import org.bunny.vehicle.util.Utils;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@RemoteProxy(creator = SpringCreator.class)
@Service
public class AdminUserService extends BaseService {

	public Page<User> getList(String json) {
		JSONObject obj = JSON.parseObject(json);

		byte type = JSON.getByte(obj, "type");
		int page = JSON.getInteger(obj, "page");

		return userRepository.findByClassification(type, new PageRequest(page, Const.PAGE_SIZE,
				Sort.Direction.DESC, "id"));
	}

	public boolean del(String json) {
		try {
			JSONArray array = JSONArray.parseArray(json);

			for (Object obj : array) {
				userRepository.delete(Integer.parseInt(obj.toString()));
			}

		} catch (Exception e) {
			log.error(e + json, e);
			return false;
		}
		return true;
	}

	public boolean save(String json) {
		JSONObject obj = JSON.parseObject(json);

		byte classification = JSON.getByte(obj, "classification");
		byte sex = JSON.getByte(obj, "sex");
		int id = JSON.getInteger(obj, "id");
		String phone = JSON.getString(obj, "phone");
		String number = JSON.getString(obj, "number");
		String password = JSON.getString(obj, "passwordNew");
		String name = JSON.getString(obj, "name");
		String idCard = JSON.getString(obj, "idCard");
		Date joinDate = JSON.getDate(obj, "joinDateYear", "joinDateMonth", "joinDateDate");
		Date birthday = JSON.getDate(obj, "birthdayYear", "birthdayMonth", "birthdayDate");

		if (id > 0 && Utils.isEmpty(number, name)) {
			return false;
		} else if (0 == id && Utils.isEmpty(number, password, name)) {
			return false;
		}

		User user;
		if (id > 0) {
			user = userRepository.findOne(id);
			if (null == user) {
				return false;
			}
		} else {
			user = new User();
		}
		user.setBirthday(birthday);
		user.setClassification(classification);
		user.setIdCard(idCard);
		user.setJoinDate(joinDate);
		user.setName(name);
		user.setNumber(number);
		user.setPhone(phone);
		user.setSex(sex);
		if (!Utils.isEmpty(password)) {
			user.setPassword(password);
		}
		return null != userRepository.save(user);
	}

}
